package entity

import (
	"errors"
	"fmt"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"

	"github.com/jinzhu/gorm"
)

//IndiClieDiviFlow2LS 零售客户认定审批变更
type IndiClieDiviFlow2LS struct {
	ID         int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	IDNO       string    `gorm:"column:IDNO"`
	CUNM       string    `gorm:"column:CUNM"`
	UTNM       string    `gorm:"column:UTNM;"`
	CUID       int       `gorm:"column:CUID"`
	UTID       int       `gorm:"column:UTID"`
	ACNO       string    `gorm:"column:ACNO"`
	BANO       string    `gorm:"column:BANO"`
	ACID       int       `gorm:"column:ACID"`
	OPDT       time.Time `gorm:"column:OPDT"`
	ITNM       string    `gorm:"column:ITNM"`
	ACBL       float64   `gorm:"column:ACBL"`
	EMNO1      string    `gorm:"column:EMNO1"`
	EMID1      int       `gorm:"column:EMID1"`
	EMNM1      string    `gorm:"-" json:"emnm1"`
	DSVL1      float64   `gorm:"column:DSVL1"`
	EMNO2      string    `gorm:"column:EMNO2"`
	EMNM2      string    `gorm:"-" json:"emnm2"`
	EMID2      int       `gorm:"column:EMID2"`
	DSVL2      float64   `gorm:"column:DSVL2"`
	EMNO3      string    `gorm:"column:EMNO3"`
	EMNM3      string    `gorm:"-" json:"emnm3"`
	EMID3      int       `gorm:"column:EMID3"`
	DSVL3      float64   `gorm:"column:DSVL3"`
	DSDT       time.Time `gorm:"column:DSDT"`
	UID        int       `gorm:"column:UID"`
	WFID       int       `gorm:"column:WFID"`
	FRID       int       `gorm:"column:FRID"`
	Progress   float64   `gorm:"-" json:"progress"`
	StepName   string    `gorm:"-" json:"stepName"`
	Status     string    `gorm:"-" json:"status"`
	STEP       int       `gorm:"-" json:"step"`
	SQR        string    `gorm:"column:SQR"`
	SQR2       string    `gorm:"column:SQR2"`
	SQR3       string    `gorm:"column:SQR3"`
	THSM       string    `gorm:"column:THSM"`
	CREATETIME time.Time `gorm:"column:CREATETIME"`
	UPDATETIME time.Time `gorm:"column:UPDATETIME"`
	STATE      string    `gorm:"column:STATE"`
	ISGHR      int       `gorm:"-" json:"isghr"`
}

//TableName User用户表名
func (IndiClieDiviFlow2LS) TableName() string {
	return "T_INDI_CLIE_DIVI2_LS"
}

//BeforeSave 保存前的触发器
func (i *IndiClieDiviFlow2LS) BeforeSave(tx *gorm.DB) (err error) {
	sqlstr := "select ACNO,BANO,OPDT,CUNM,ITNM,UTNM,CUID,UTID from V_INDI_ACCO_FLOW WHERE ID=?"
	row := tx.Raw(sqlstr, i.ACID).Row()
	row.Scan(&i.ACNO, &i.BANO, &i.OPDT, &i.CUNM, &i.ITNM, &i.UTNM, &i.CUID, &i.UTID)
	sum := i.DSVL1 + i.DSVL2 + i.DSVL3
	if sum != 100 {
		return errors.New("占比之和必须为100！")
	}
	var emid1, emid2, emid3 int
	sql := "select ID,SysUserName from T_SysUser where SysUserID=?"
	row = tx.Raw(sql, i.EMNO1).Row()
	row.Scan(&emid1, &i.SQR)
	if emid1 == 0 {
		return fmt.Errorf("员工号1:%s在系统中没有找到！", i.EMNO1)
	}
	i.EMID1 = emid1
	if i.DSVL2 > 0 {
		row = tx.Raw(sql, i.EMNO2).Row()
		row.Scan(&emid2, &i.SQR2)
		if emid2 == 0 {
			return fmt.Errorf("员工号2:%s在系统中没有找到！", i.EMNO2)
		}
		i.EMID2 = emid2
	}
	row = tx.Raw("select ID,SysUserName from T_SysUser where SysUserID=? AND ISLSGHR=1", i.EMNO3).Row()
	row.Scan(&emid3, &i.SQR3)
	if emid3 == 0 {
		return fmt.Errorf("员工号:【%s】无管户资格，不是管户人", i.EMNO3)
	}
	i.EMID3 = emid3

	if i.DSVL3 < 10 {
		return fmt.Errorf("管户人【%s】的占比最少10%", i.EMNO3)
	}
	sql = "select emid from t_indi_acco_divi a inner join t_indi_acco b on a.acid=b.id where a.iswo=0 and wodt is null and b.acid=?"
	row = tx.Raw(sql, i.ACID).Row()
	var count int
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("客户:%s(%s)的账号%s(%s)没有认定，请走业绩确认审批流程！", i.CUNM, i.IDNO, i.ACNO, i.BANO)
	}
	if i.ID == 0 {
		sql = "select count(a.ID) from T_INDI_CLIE_DIVI2_LS a inner join T_FLOW_RUN b on a.FRID=b.ID where b.STATE=0 and a.acid=?"
		row = tx.Raw(sql, i.ACID).Row()
		var count2 int
		row.Scan(&count2)
		if count2 > 0 {
			return fmt.Errorf("客户:%s(%s)的账号%s(%s)已经在申请中，不能重复申请！", i.CUNM, i.IDNO, i.ACNO, i.BANO)
		}
	}
	sql = "select dbo.GetBackDATE()"
	row = tx.Raw(sql).Row()
	var dsdt time.Time
	row.Scan(&dsdt)
	if i.DSDT.Unix() < dsdt.Unix() {
		return fmt.Errorf("客户:%s(%s)的账号%s(%s)的变更日期不能小于%s！%s", i.CUNM, i.IDNO, i.ACNO, i.BANO, dsdt.Format("20060102"), i.DSDT.Format("20060102"))
	}
	if i.ID > 0 {
		row := base.DB.Model(IndiClieDiviFlow2LS{}).Where("ID=?", i.ID).Select("FRID", "WFID").Row()
		row.Scan(&i.FRID, i.WFID)
	}
	if i.FRID == 0 {
		runid, err := workflow.Create(28, i.UID, tx)
		if err != nil {
			return err
		}
		i.FRID = runid
	}

	// sqlstr = `UPDATE T_INDI_CLIE_DIVI2_LS SET  STATE=CASE WHEN B.STATE=0 THEN '正在运行'
	// WHEN B.STATE=1 THEN '已完结'
	// WHEN B.STATE=2 THEN '已中止'
	// END
	// FROM T_INDI_CLIE_DIVI2_LS A
	// INNER JOIN T_FLOW_RUN B ON A.FRID=B.ID`

	return
}

func (i *IndiClieDiviFlow2LS) AfterDelete(tx *gorm.DB) (err error) {
	if i.FRID > 0 {
		return workflow.Delete(i.FRID)
	}
	return nil
}

// AfterFind 查询后触发器
func (i *IndiClieDiviFlow2LS) AfterFind(tx *gorm.DB) (err error) {
	sqlEx := "select SysUserName from T_SysUser where ID = ?"
	row := tx.Raw(sqlEx, i.EMID1).Row()
	row.Scan(&i.EMNM1)
	if i.DSVL2 > 0 {
		row := tx.Raw(sqlEx, i.EMID2).Row()
		row.Scan(&i.EMNM2)
	}
	if i.DSVL3 > 0 {
		row := tx.Raw(sqlEx, i.EMID3).Row()
		row.Scan(&i.EMNM3)
	}
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	sqlEx = "select count(*) ISGHR from T_SysUser where ID in(select EMID3 from T_INDI_CLIE_DIVI2_LS where FRID=?) AND ISLSGHR=1"
	row = tx.Raw(sqlEx, i.FRID).Row()
	row.Scan(&i.ISGHR)

	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}

	return
}

func IndiClieDiviFlow2LSEF() base.EntityFunc {
	return func() interface{} {
		entity := IndiClieDiviFlow2LS{}
		return &entity
	}
}
func IndiClieDiviFlow2LSESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []IndiClieDiviFlow2LS
		return &entities
	}
}

func init() {
	dao := base.NewDefaultDao(IndiClieDiviFlow2LSEF(), IndiClieDiviFlow2LSESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "28")
	//强制提交
	filter.SetAdditional("manager", "2:48,12:101,22:110")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("IndiClieDiviFlow2LS", dao)

}
